import jwt
from django.conf import settings
from rest_framework.authentication import BaseAuthentication, get_authorization_header
from rest_framework import exceptions
import time

# 全局用户数据（不使用数据库）
GLOBAL_USERS = {"admin": {"id": 1, "username": "admin", "password": "123456"}}


class SimpleUser:
    """简单用户类，模拟数据库用户"""

    def __init__(self, user_data):
        self.pk = user_data["id"]
        self.id = user_data["id"]
        self.username = user_data["username"]
        self.password = user_data["password"]
        # Django用户认证所需的属性
        self.is_authenticated = True  # JWT认证成功的用户都是已认证状态
        self.is_active = True  # 用户是激活状态
        self.is_anonymous = False  # 不是匿名用户
        self.is_staff = False  # 不是管理员
        self.is_superuser = False  # 不是超级用户


def generate_jwt(user):
    expire_time = int(time.time() + settings.KEY_TIME)
    return jwt.encode(
        {"userid": user.pk, "username": user.username, "exp": expire_time},
        key=settings.SECRET_KEY,
        algorithm="HS256",
    )


class JWTAuthentication(BaseAuthentication):
    """
    Authorization: JWT 401f7ac837da42b97f613d789819ff93537bee6a
    """

    keyword = "JWT"
    model = None

    def authenticate(self, request):
        auth = get_authorization_header(request).split()

        print(auth)
        print(
            "======================================================================================"
        )

        if not auth or auth[0].lower() != self.keyword.lower().encode():
            return None
        if len(auth) == 1:
            msg = "Authorization不可用！"
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = "Authorization不可用！应该提供一个空格！"
            raise exceptions.AuthenticationFailed(msg)

        try:
            jwt_token = auth[1]
            jwt_info = jwt.decode(jwt_token, settings.SECRET_KEY, algorithms=["HS256"])
            userid = jwt_info.get("userid")
            username = jwt_info.get("username")

            # 从全局用户中查找用户
            user_data = None
            for user_key, user_info in GLOBAL_USERS.items():
                if user_info["id"] == userid and user_info["username"] == username:
                    user_data = user_info
                    break

            if not user_data:
                msg = "用户不存在！"
                raise exceptions.AuthenticationFailed(msg)

            user = SimpleUser(user_data)
            return (user, jwt_token)
        except jwt.DecodeError:
            msg = "token解码失败！无效的token格式"
            raise exceptions.AuthenticationFailed(msg)
        except jwt.ExpiredSignatureError:
            msg = "token已过期！"
            raise exceptions.AuthenticationFailed(msg)
        except jwt.InvalidTokenError:
            msg = "token无效！"
            raise exceptions.AuthenticationFailed(msg)
        except UnicodeError:
            msg = "token格式错误！"
            raise exceptions.AuthenticationFailed(msg)
        except Exception as e:
            msg = f"认证失败：{str(e)}"
            raise exceptions.AuthenticationFailed(msg)
